package com.texaco.chapasFutbol;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.andengine.audio.music.MusicFactory;
import org.andengine.audio.sound.Sound;
import org.andengine.audio.sound.SoundFactory;
import org.andengine.engine.camera.SmoothCamera;
import org.andengine.engine.camera.ZoomCamera;
import org.andengine.engine.options.EngineOptions;
import org.andengine.engine.options.ScreenOrientation;
import org.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.andengine.entity.scene.Scene;
import org.andengine.extension.svg.opengl.texture.atlas.bitmap.SVGBitmapTextureAtlasTextureRegionFactory;
import org.andengine.opengl.font.Font;
import org.andengine.opengl.font.FontFactory;
import org.andengine.opengl.texture.TextureOptions;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.andengine.opengl.texture.atlas.bitmap.BuildableBitmapTextureAtlas;
import org.andengine.opengl.texture.atlas.bitmap.source.IBitmapTextureAtlasSource;
import org.andengine.opengl.texture.atlas.buildable.builder.BlackPawnTextureAtlasBuilder;
import org.andengine.opengl.texture.atlas.buildable.builder.ITextureAtlasBuilder.TextureAtlasBuilderException;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.texture.region.TextureRegionFactory;
import org.andengine.opengl.texture.region.TiledTextureRegion;
import org.andengine.ui.activity.BaseGameActivity;
import org.andengine.util.debug.Debug;
import org.andengine.util.progress.IProgressListener;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.util.DisplayMetrics;
import android.view.KeyEvent;

import com.texaco.chapasFutbol.entidades.Campo;
import com.texaco.chapasFutbol.entidades.Chapa;
import com.texaco.chapasFutbol.entidades.Game;
import com.texaco.chapasFutbol.entidades.Halo;
import com.texaco.chapasFutbol.entidades.Hud;
import com.texaco.chapasFutbol.entidades.TiradorChapa;
import com.texaco.chapasFutbol.resources.Atlas;
import com.texaco.chapasFutbol.resources.Resource;
import com.texaco.chapasFutbol.resources.Resources;
import com.texaco.chapasFutbol.scene.CreditScene;
import com.texaco.chapasFutbol.scene.GameScene;
import com.texaco.chapasFutbol.scene.MenuPrincipalScene;
import com.texaco.chapasFutbol.scene.SummaryScene;
import com.texaco.chapasFutbol.sound.SoundHandler;

public class ChapasFutbolActivity extends BaseGameActivity {

	public final int DIALOG_CONFIRMATION_ID = 0;
	
	public Scene mSplashScene;
	private Map<String, Font> fontMap;

	public ZoomCamera mCamera;
	private BitmapTextureAtlas mBackGroundTextureAtlas;
	private BitmapTextureAtlas mSpritesTextureAtlas;
	private BitmapTextureAtlas mTiradorTextureAtlas;
	private BitmapTextureAtlas mHudTextureAtlas;
	private BitmapTextureAtlas mButtonsTextureAtlas;
	private Map<String, BitmapTextureAtlas>atlasMap = new HashMap<String, BitmapTextureAtlas>();
	
	public TiledTextureRegion mVectorTextureRegion;
	
//	public BitmapTextureAtlas mBarraTiempoTextureAtlas;
//	public ITextureRegion mBarraTiempoTextureRegion;
	
	protected SoundHandler soundHandler;
	
	private Map<String, ITextureRegion> shapesMaps = 
			new HashMap<String, ITextureRegion>();
	private Map<String, ITextureRegion> vectorMap;

	private Game game;

	public BitmapTextureAtlas mSplashTexture;
	public ITextureRegion mSplashTextureAtlas;

	/* Recursos para el menú contextual. */
	public BitmapTextureAtlas mMenuTexture;
	public ITextureRegion mMenuResetTextureRegion;
	public ITextureRegion mContinueTextureRegion;
	public ITextureRegion mMenuQuitTextureRegion;
	public ITextureRegion mMenuPrincipalTextureRegion;

	/* Vector fuerza. */
	private BuildableBitmapTextureAtlas mBuildableBitmapTextureAtlas;
	
	/*
	 * Recursos opciones
	 */
	private BitmapTextureAtlas mBgOptionsTextureAtlas;
	private BitmapTextureAtlas mBtOptionsTextureAtlas;
	
	/*
	 * Recursos para el menú principal
	 */
	private BitmapTextureAtlas mBgMenuPrincipalTextureAtlas;

	/*
	 * Atlas para el fondo del cartel.  
	 */
	private BitmapTextureAtlas mBgCartelTextureAtlas;

	public EngineOptions onCreateEngineOptions() {
		DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
		this.mCamera = new SmoothCamera(0, 0, 
				this.getResources().getInteger(R.integer.camera_width), //(Configurable.CAMERA_HEIGHT * ((float)dm.widthPixels / (float)dm.heightPixels)), 
				(float)this.getResources().getInteger(R.integer.camera_width) / ((float)dm.widthPixels / (float)dm.heightPixels), //(Configurable.CAMERA_HEIGHT, 
				this.getResources().getInteger(R.integer.cam_max_vel_x), 
				this.getResources().getInteger(R.integer.cam_max_vel_y), 
				this.getResources().getInteger(R.integer.cam_max_vel_zoom));

		this.mCamera.setBoundsEnabled(true);
		this.mCamera.setBounds(
				-this.getResources().getInteger(R.integer.camera_margin_x), 
				-this.getResources().getInteger(R.integer.camera_margin_y), 
				this.getResources().getInteger(R.integer.camera_margin_x) + this.getResources().getInteger(R.integer.game_place_width), 
				this.getResources().getInteger(R.integer.camera_margin_y) + this.getResources().getInteger(R.integer.game_place_height));

		final EngineOptions engineOptions = new EngineOptions(true,
				ScreenOrientation.LANDSCAPE_FIXED, new RatioResolutionPolicy(
				        dm.widthPixels, dm.heightPixels), this.mCamera);

		engineOptions.getAudioOptions().setNeedsSound(true);
		engineOptions.getAudioOptions().setNeedsMusic(true);
		engineOptions.getTouchOptions().setNeedsMultiTouch(true);

		
		return engineOptions;
	}
	
	/**
	 * Método que crea los contenidos de los diálogos a mostrar.
	 */
	@Override
	protected Dialog onCreateDialog(int id) {
		
		AlertDialog.Builder builder = 
				new AlertDialog.Builder(ChapasFutbolActivity.this);
		
		switch(id) {
	   
			case DIALOG_CONFIRMATION_ID:
		    	
				return builder.setMessage(R.string.texto_confirmar_salir)
			       .setCancelable(false)
			       .setPositiveButton(R.string.texto_confirmar_si, 
			    		   new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			                ChapasFutbolActivity.this.finish();
			           }
			       })
			       .setNegativeButton(R.string.texto_confirmar_no, 
			    		   new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			                dialog.cancel();
			           }
			       }).create();
		    	
	    }
		
		return super.onCreateDialog(id);
	}

	/**
	 * Los diálogos deben mostrarse sobre la misma hebra de la interfaz.
	 * 
	 * @param id
	 */
	public void showMessage(final int id) {
		this.runOnUiThread(new Runnable() {
			public void run() {
				ChapasFutbolActivity.this.showDialog(id);
			}
		});
	}
	
	/**
	 * Método donde cargamos los recursos
	 */
	public void onCreateResources(final OnCreateResourcesCallback pOnCreateResourcesCallback) {
		try {
			onCreateResourcesAsync(new IProgressListener() {
				
				public void onProgressChanged(int pProgress) {
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}

		pOnCreateResourcesCallback.onCreateResourcesFinished();
	}
	
	public void onCreateResourcesAsync(final IProgressListener pProgressListener) 
			throws Exception {
		//Raiz de los recursos
		BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
		FontFactory.setAssetBasePath("font/");
		SoundFactory.setAssetBasePath("mfx/");
		MusicFactory.setAssetBasePath("mfx/");

		this.fontMap = new HashMap<String, Font>();
		for(Entry<String, com.texaco.chapasFutbol.resources.Font> entry : Resources.fonts.entrySet()){
			this.fontMap.put(entry.getKey(), FontFactory.createFromAsset(this.getFontManager(),
					this.getTextureManager(), 512, 512, TextureOptions.BILINEAR,
					this.getAssets(), 
					entry.getValue().getPath(), 
					entry.getValue().getSize(), true, 
					entry.getValue().getColor()));
			this.fontMap.get(entry.getKey()).load();
		}
	
		/* Cargamos todos los sonidos y la musica necesaria para el juego. */
		try {
			
			soundHandler = new SoundHandler();
			for(Entry<String, String> soundEntry : Resources.soundFXResources.entrySet()){
				
				Sound s = SoundFactory.createSoundFromAsset(
						this.getSoundManager(), this, soundEntry.getValue());
				
				soundHandler.putFx(soundEntry.getKey(), s);
			}
			
			for(Entry<String, String> musicEntry : Resources.soundMusicResources.entrySet()){
				soundHandler.putMusic(musicEntry.getKey(), 
						MusicFactory.createMusicFromAsset(
					this.getMusicManager(), this, musicEntry.getValue()));
			}
			
		} catch (final IOException e) {
			Debug.e(e);
		}
	
		/* Cargamos los recursos para el Splash. */
		this.mSplashTexture = new BitmapTextureAtlas(this.getTextureManager(),
				(int) this.mCamera.getWidth(), (int) this.mCamera.getHeight(), TextureOptions.DEFAULT);
		
		this.mSplashTextureAtlas = BitmapTextureAtlasTextureRegionFactory
				.createFromAsset(this.mSplashTexture, this, "img-pantalla-splash.jpg", 
						0, 0);
		this.mSplashTexture.load();
	
		pProgressListener.onProgressChanged(100);
	}
	
	public Scene onCreateSceneAsync(final IProgressListener pProgressListener) 
			throws Exception {
		game = new Game(this);
		pProgressListener.onProgressChanged(100);
    	soundHandler.playFx(Resources.SOUND_SPLASH);
		return game.getSceneHandler().getScene();
	}
	
	public void onCreateScene(final OnCreateSceneCallback pOnCreateSceneCallback) {
		Scene scene = null;
		try {
			scene = onCreateSceneAsync(new IProgressListener() {
				
				public void onProgressChanged(int pProgress) {
					// TODO Auto-generated method stub
					
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
		pOnCreateSceneCallback.onCreateSceneFinished(scene);
	}
	
	@Override
	public boolean onKeyUp(final int pKeyCode, final KeyEvent pEvent) {
		if (pKeyCode == KeyEvent.KEYCODE_MENU){
			if (game.getSceneHandler().getGame().hasChildScene()) {
				/* Quitar el menu contextual. */
				game.getSceneHandler().getGame().getChildScene().back(); //Lo generalizo por que es posible que haya varios menú contextuales.
			} else {
				if(game.getOpciones().isMultiplayer()){
					game.loadMenuExitOnline();
				}else{
					game.loadMenuContextual();
				}
			}
			return true;
		} else if(pKeyCode == KeyEvent.KEYCODE_BACK){
			/*
			 * Se pulsa la tecla de retroceso
			 */
			game.keyBack();
			return true;
		}else{
			return super.onKeyDown(pKeyCode, pEvent);
		}
	}
	
	public Map<String, ITextureRegion> getShapesMaps() {
		return shapesMaps;
	}

	public void onPopulateScene(Scene pScene, OnPopulateSceneCallback pOnPopulateSceneCallback) throws Exception {
		
		new Thread(new Runnable() {
			
			public void run() {
				loadResources();
				game.iniciaSpritesJuego();
				runOnUiThread(new Runnable() {
					public void run() {
						game.getSceneHandler().setMenuPrincipal();
						getSoundHandler().playMusic(Resources.MUSIC_PRINCIPAL, true);
						mEngine.setScene(game.getSceneHandler().getScene());
					}
				});
			}
		}).start();
		pOnPopulateSceneCallback.onPopulateSceneFinished();
	}
	
	private void loadResources() {
		// Cargo los recursos vectoriales
		SVGBitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
		BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
			
		/*
		 * He experimentado ciertos problemas, Por ejemplo, poniendo el tamaño
		 * del atlas (int) CAMERA_WIDTH + 1000, (int) CAMERA_HEIGHT + 1000 La
		 * pantalla se pone todo en negro. Desconozco cuales son los límites
		 * pero desde luego esta no es la forma de cargar los recursos A ver si
		 * el NONO sepone las pilas y empezamos a usar los spritesheet.
		 */
		this.mBackGroundTextureAtlas = new BitmapTextureAtlas(
				this.getTextureManager(), 
	//			Campo.WIDTH, 
	//			Campo.HEIGHT,
	//			397, //TODO: alto de la textura de repetición. Habría que establecerlo como parámetro o en recursos.
	//			Campo.HEIGHT,
				1024, 256,
				TextureOptions.REPEATING_NEAREST);
		
		/*
		 * Atlas donde vamos a meter la imagenes correspondientes a los sprites.
		 * FIXME: HAY QUE CREAR OTRO ATLAS PARA EL HALO Y PONERLE LAS DIMENSIONES CORRECTAS A ESTE.
		 */
		this.mSpritesTextureAtlas = new BitmapTextureAtlas(
				this.getTextureManager(), (int)this.mCamera.getWidth(),
				(int)this.mCamera.getHeight(), TextureOptions.BILINEAR);
	
		/*
		 * Atlas donde vamos a poner las partes del hud.
		 */
		this.mHudTextureAtlas = new BitmapTextureAtlas(
				this.getTextureManager(), 800, 150, TextureOptions.BILINEAR);
	
		/*
		 * Atlas donde vamos a poner las imagenes del tirador.
		 */
		this.mTiradorTextureAtlas = new BitmapTextureAtlas(
				this.getTextureManager(), 712, 112, TextureOptions.BILINEAR);
		
		this.mBgOptionsTextureAtlas = new BitmapTextureAtlas(
				this.getTextureManager(), 1280, 800, TextureOptions.BILINEAR);
		
		this.mBtOptionsTextureAtlas = new BitmapTextureAtlas(
				this.getTextureManager(), 311, 120, TextureOptions.BILINEAR);
		
		/*
		 * Atlas para los recursos del menú principal.
		 */
		this.mBgMenuPrincipalTextureAtlas = new BitmapTextureAtlas(
				this.getTextureManager(), 1280, 800, TextureOptions.BILINEAR);
		
		this.mButtonsTextureAtlas = new BitmapTextureAtlas(
				this.getTextureManager(), 563, 128, TextureOptions.BILINEAR);
		
		this.mBgCartelTextureAtlas = new BitmapTextureAtlas(
				this.getTextureManager(), 796, 845, TextureOptions.BILINEAR);
		
		/**
		 * Creamos los objetos que vamos a meter en el atlas del background.
		 */
		shapesMaps.put(Game.CAMPO_SHAPE, BitmapTextureAtlasTextureRegionFactory
				.createFromAsset(this.mBackGroundTextureAtlas, this,
						Campo.IMAGEN, 0, 0));
		shapesMaps.get(Game.CAMPO_SHAPE).setTextureSize(this.getResources().getInteger(R.integer.game_place_width) + this.getResources().getInteger(R.integer.camera_margin_x) * 2, 
				this.getResources().getInteger(R.integer.game_place_height) + this.getResources().getInteger(R.integer.camera_margin_y) * 2);
	
		/**
		 * Creamos los objetos que van a ir dentro del atlas de los sprites
		 */
		BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				this.mSpritesTextureAtlas, this, "balones-y-chapas.png", 0, 0);
		
		shapesMaps.put(Game.HALO_SHAPE, BitmapTextureAtlasTextureRegionFactory
				.createFromAsset(this.mSpritesTextureAtlas, this,
						Halo.IMAGEN, Chapa.WIDTH * 7, 0));
	
		BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				this.mHudTextureAtlas, this, "hud.png", 0, 0);
	
		/*
		 * RECURSOS ESCENA OPCIONES
		 */
		//Atlas del bacground de las opciones.
		BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				this.mBgOptionsTextureAtlas, this, "bg-opciones.jpg", 0, 0);
		
		//Atlas de los botones de las opciones.
		BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				this.mBtOptionsTextureAtlas, this, "select-opciones.png", 0, 0);
		
//		pProgressListener.onProgressChanged(50);
	
		/*
		 * RECURSOS PARA EL MENÚ PRINCIPAL
		 */
		//Atlas del bacground de las opciones.
		BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				this.mBgMenuPrincipalTextureAtlas, this, "bg-intro.jpg", 0, 0);
		
		BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				this.mButtonsTextureAtlas, this, "botones-opciones.png", 0, 0);
		
		BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				this.mBgCartelTextureAtlas, this, "panel-exit-credits.png", 0, 0);
		
		// Recursos para las imágenes de la música y el sonido.
		
		this.mBackGroundTextureAtlas.load();
		this.mSpritesTextureAtlas.load();
		this.mTiradorTextureAtlas.load();
		this.mHudTextureAtlas.load();
		this.mBgOptionsTextureAtlas.load();
		this.mBtOptionsTextureAtlas.load();
		this.mBgMenuPrincipalTextureAtlas.load();
		this.mButtonsTextureAtlas.load();
		this.mBgCartelTextureAtlas.load();
	//	this.mBarraTiempoTextureAtlas.load();
	
		/* Cargamos todos los sonidos y la musica necesaria para el juego. */
		try {
			SoundFactory.setAssetBasePath("mfx/");
			MusicFactory.setAssetBasePath("mfx/");
			
			soundHandler = new SoundHandler();
			for(Entry<String, String> soundEntry : Resources.soundFXResources.entrySet()){
				
				Sound s = SoundFactory.createSoundFromAsset(
						this.getSoundManager(), this, soundEntry.getValue());
				
				soundHandler.putFx(soundEntry.getKey(), s);
			}
			
			for(Entry<String, String> musicEntry : Resources.soundMusicResources.entrySet()){
				soundHandler.putMusic(musicEntry.getKey(), 
						MusicFactory.createMusicFromAsset(
					this.getMusicManager(), this, musicEntry.getValue()));
			}
			
		} catch (final IOException e) {
			Debug.e(e);
		}
	
		this.mBuildableBitmapTextureAtlas = new BuildableBitmapTextureAtlas(
				this.getTextureManager(), (int) this.mCamera.getWidth(), (int) this.mCamera.getHeight(), 
				TextureOptions.BILINEAR);
		
		this.mVectorTextureRegion = BitmapTextureAtlasTextureRegionFactory.
				createTiledFromAsset(this.mBuildableBitmapTextureAtlas, this, "lineas-tiro.png", 1, 5);

		this.vectorMap = new HashMap<String, ITextureRegion>();
		for(Entry<String, Resource> entry : Resources.vectors.entrySet()){
			this.vectorMap.put(entry.getKey(), SVGBitmapTextureAtlasTextureRegionFactory
					.createFromAsset(this.mBuildableBitmapTextureAtlas, this, 
							entry.getValue().getFile(), entry.getValue().getWidth(), 
							entry.getValue().getHeight()));
		}
		
		try {
			this.mBuildableBitmapTextureAtlas.build(
					new BlackPawnTextureAtlasBuilder<IBitmapTextureAtlasSource, 
					BitmapTextureAtlas>(0, 1, 1));
			this.mBuildableBitmapTextureAtlas.load();
		} catch (final TextureAtlasBuilderException e) {
			Debug.e(e);
		}
		
		//Boton OK
		shapesMaps.put(TiradorChapa.SHAPE_TIRADOR_OK, TextureRegionFactory.extractFromTexture(
				this.mTiradorTextureAtlas, TiradorChapa.SHAPE_TIRADOR_OK_X,
				TiradorChapa.SHAPE_TIRADOR_OK_Y, TiradorChapa.TIRADOR_OK_WIDTH,
				TiradorChapa.TIRADOR_OK_HEIGHT));
		
		//Boton CANCEL
		shapesMaps.put(TiradorChapa.SHAPE_TIRADOR_CANCEL, TextureRegionFactory.extractFromTexture(
				this.mTiradorTextureAtlas, TiradorChapa.SHAPE_TIRADOR_CANCEL_X,
				TiradorChapa.SHAPE_TIRADOR_CANCEL_Y, TiradorChapa.TIRADOR_CANCEL_WIDTH,
				TiradorChapa.TIRADOR_CANCEL_HEIGHT));
		
		/* BOTONES OPCIONES */
		shapesMaps.put(Game.OPTIONS_BACKGROUND_SHAPE, TextureRegionFactory.extractFromTexture(
				this.mBgOptionsTextureAtlas, 0, 0, 1280, 800));
		
		shapesMaps.put(Game.OPTIONS_MINUS_SHAPE, TextureRegionFactory.extractFromTexture(
				this.mBtOptionsTextureAtlas, 0, 0, 62, 120));
		
		shapesMaps.put(Game.OPTIONS_PLUS_SHAPE, TextureRegionFactory.extractFromTexture(
				this.mBtOptionsTextureAtlas, 249, 0, 311-249,120));
		
		shapesMaps.put(Game.OPTIONS_VALUE_SHAPE, TextureRegionFactory.extractFromTexture(
				this.mBtOptionsTextureAtlas, 69, 0, 240-69, 120));
		
		/* BOTONES PARA EL MENÚ PRINCIPAL */
		shapesMaps.put(Game.PRINCIPAL_BACKGROUND_SHAPE, TextureRegionFactory.extractFromTexture(
				this.mBgMenuPrincipalTextureAtlas, 0, 0, 1280, 800));
		
		/* Partes del HUD */
		// HUD.
		shapesMaps.put(Hud.SHAPE_HUD, TextureRegionFactory.extractFromTexture(
				this.mHudTextureAtlas, Hud.SHAPE_HUD_X,
				Hud.SHAPE_HUD_Y, Hud.HUD_WIDTH,
				Hud.HUD_HEIGHT));
		// Logo local.
		shapesMaps.put(Hud.SHAPE_LOGO_LOCAL, TextureRegionFactory.extractFromTexture(
				this.mHudTextureAtlas, Hud.SHAPE_LOGO_LOCAL_X,
				Hud.SHAPE_LOGO_LOCAL_Y, Hud.LOGO_LOCAL_WIDTH,
				Hud.LOGO_LOCAL_HEIGHT));
		// Logo visitante.
		shapesMaps.put(Hud.SHAPE_LOGO_VISITANTE, TextureRegionFactory.extractFromTexture(
				this.mHudTextureAtlas, Hud.SHAPE_LOGO_VISITANTE_X,
				Hud.SHAPE_LOGO_VISITANTE_Y, Hud.LOGO_VISITANTE_WIDTH,
				Hud.LOGO_VISITANTE_HEIGHT));
		// Marcador.
		shapesMaps.put(Hud.SHAPE_MARCADOR, TextureRegionFactory.extractFromTexture(
				this.mHudTextureAtlas, Hud.SHAPE_MARCADOR_X,
				Hud.SHAPE_MARCADOR_Y, Hud.MARCADOR_WIDTH,
				Hud.MARCADOR_HEIGHT));
		// Tiempo
		shapesMaps.put(Hud.SHAPE_TIEMPO, TextureRegionFactory.extractFromTexture(
				this.mHudTextureAtlas, Hud.SHAPE_TIEMPO_X,
				Hud.SHAPE_TIEMPO_Y, Hud.TIEMPO_WIDTH,
				Hud.TIEMPO_HEIGHT));
				
		shapesMaps.put(Game.BOTON_ANTERIOR_SHAPE, TextureRegionFactory
				.extractFromTexture(this.mButtonsTextureAtlas, 0, 0,
						247, 128));
		
		shapesMaps.put(Game.BOTON_SIGUIENTE_SHAPE, TextureRegionFactory
				.extractFromTexture(this.mButtonsTextureAtlas, 316, 0,
						563 - 316, 128));
		
		shapesMaps.put(Game.BG_CARTEL_SHAPE, TextureRegionFactory
				.extractFromTexture(this.mBgCartelTextureAtlas, 0, 0,
						796, 845));
	
		/*
		 * Automatizacion de recursos.
		 * Creacion del recurso.
		 */
		for(Entry<String, Atlas> atlas : Resources.graphicResources.entrySet()){
			atlasMap.put(atlas.getKey(), new BitmapTextureAtlas(
					this.getTextureManager(), atlas.getValue().getWidth(), atlas.getValue().getHeight(),
					TextureOptions.BILINEAR));
			
			if(atlas.getValue().getFile() == null || atlas.getValue().getFile().equals("")){
				for(Entry<String, Resource>entry : atlas.getValue().getResources().entrySet()){
					shapesMaps.put(entry.getKey(), BitmapTextureAtlasTextureRegionFactory.
							createFromAsset(atlasMap.get(atlas.getKey()), this, 
								entry.getValue().getFile(),
								entry.getValue().getxPos(),   //FIXME: LAS POSICIONES DEBEN DE SER CALCULADAS, PARA DEFINIR SOLAMENTE LAS DIMENSIONES DEL SPRITE.
								entry.getValue().getyPos())); //FIXME: LAS POSICIONES DEBEN DE SER CALCULADAS, PARA DEFINIR SOLAMENTE LAS DIMENSIONES DEL SPRITE.
				}
				atlasMap.get(atlas.getKey()).load();
			}else{
				BitmapTextureAtlasTextureRegionFactory.createFromAsset(
						atlasMap.get(atlas.getKey()), this, atlas.getValue().getFile(), 0, 0);
				
				atlasMap.get(atlas.getKey()).load();
				
				for(Entry<String, Resource>entry : atlas.getValue().getResources().entrySet()){
					shapesMaps.put(entry.getKey(), TextureRegionFactory.extractFromTexture(
							atlasMap.get(atlas.getKey()), entry.getValue().getxPos(),
							entry.getValue().getyPos(), entry.getValue().getWidth(),
							entry.getValue().getHeight()));
				}
				
			}
		}
	
//		pProgressListener.onProgressChanged(100);		
	}

	public SoundHandler getSoundHandler() {
		return this.soundHandler;
	}

	public Map<String, Font> getFontMap(){
		return this.fontMap;
	}
	
	public Map<String, ITextureRegion> getVectorMap() {
		
		return this.vectorMap;
	}
	
	public void onStop() {
		
		super.onStop();
		
		if (soundHandler != null){
			if (game.getSceneHandler().getScene() instanceof MenuPrincipalScene){
				soundHandler.pauseMusicLabel(Resources.MUSIC_PRINCIPAL);
			}else if(game.getSceneHandler().getScene() instanceof CreditScene){
				soundHandler.pauseMusicLabel(Resources.MUSIC_CREDITS);
			}else if(game.getSceneHandler().getScene() instanceof SummaryScene){
				soundHandler.pauseMusicLabel(Resources.MUSIC_SUMMARY);
			}else if(game.getSceneHandler().getScene() instanceof GameScene){
				soundHandler.pauseMusicLabel(Resources.MUSIC_CROWD);
			}
		}
	}

	public void onResume() {
		
		super.onResume();
		
		if (soundHandler != null){
			if (game.getSceneHandler().getScene() instanceof MenuPrincipalScene){
				soundHandler.playMusic(Resources.MUSIC_PRINCIPAL, true);
			}else if(game.getSceneHandler().getScene() instanceof CreditScene){
				soundHandler.playMusic(Resources.MUSIC_CREDITS, true);
			}else if(game.getSceneHandler().getScene() instanceof SummaryScene){
				soundHandler.playMusic(Resources.MUSIC_SUMMARY, true);
			}else if(game.getSceneHandler().getScene() instanceof GameScene){
				soundHandler.playMusic(Resources.MUSIC_CROWD, true);
			}
		}
    }
}

